
"use client";

import { useState, useEffect } from 'react';
import { useRouter, useParams } from 'next/navigation';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { useToast } from '@/hooks/use-toast';
import { getPostBySlug, updatePost, Post } from '@/lib/posts';
import { ArrowLeft } from 'lucide-react';
import Link from 'next/link';
import { notFound } from 'next/navigation';
import { Skeleton } from '@/components/ui/skeleton';

export default function EditPostPage() {
  const router = useRouter();
  const params = useParams();
  const slug = params.slug as string;

  const { toast } = useToast();
  const [post, setPost] = useState<Post | null | undefined>(undefined);
  const [title, setTitle] = useState('');
  const [content, setContent] = useState('');
  const [tags, setTags] = useState('');
  const [isSubmitting, setIsSubmitting] = useState(false);

  useEffect(() => {
    if (slug) {
      const existingPost = getPostBySlug(slug);
      if (existingPost && existingPost.isLocal) {
        setPost(existingPost);
        setTitle(existingPost.title);
        setContent(existingPost.content);
        setTags(existingPost.tags.join(', '));
      } else {
        setPost(null); // Post not found or is not a local post
      }
    }
  }, [slug]);

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    if (!title || !content) {
      toast({
        variant: 'destructive',
        title: '错误',
        description: '标题和内容不能为空。',
      });
      return;
    }
    
    setIsSubmitting(true);

    try {
      const tagsArray = tags.split(',').map(tag => tag.trim()).filter(Boolean);
      const updatedPost = updatePost(slug, { title, content, tags: tagsArray });

      toast({
        title: '成功！',
        description: '您的文章已成功更新。',
      });
      
      if (updatedPost) {
        router.push(`/posts/${updatedPost.slug}`);
      } else {
        router.push('/');
      }
    } catch (error) {
       toast({
        variant: 'destructive',
        title: '错误',
        description: '更新文章时出错，请稍后再试。',
      });
      setIsSubmitting(false);
    }
  };

  if (post === undefined) {
    return (
      <div className="max-w-4xl mx-auto">
        <Skeleton className="h-10 w-1/4 mb-6" />
        <Card>
          <CardHeader>
             <Skeleton className="h-8 w-1/2 mb-2" />
          </CardHeader>
          <CardContent className="space-y-6">
             <Skeleton className="h-10 w-full" />
             <Skeleton className="h-40 w-full" />
             <Skeleton className="h-10 w-full" />
             <Skeleton className="h-10 w-full" />
          </CardContent>
        </Card>
      </div>
    );
  }

  if (!post) {
    notFound();
  }


  return (
    <div className="max-w-4xl mx-auto">
       <Button variant="ghost" asChild className="mb-6">
          <Link href={`/posts/${slug}`}>
            <ArrowLeft className="mr-2 h-4 w-4" />
            返回文章
          </Link>
        </Button>
      <Card>
        <CardHeader>
          <CardTitle className="font-headline text-3xl">编辑文章</CardTitle>
        </CardHeader>
        <CardContent>
          <form onSubmit={handleSubmit} className="space-y-6">
            <div>
              <label htmlFor="title" className="block text-sm font-medium text-foreground mb-2">
                文章标题
              </label>
              <Input
                id="title"
                value={title}
                onChange={(e) => setTitle(e.target.value)}
                placeholder="请输入文章标题"
                className="text-lg"
                required
              />
            </div>
            <div>
              <label htmlFor="content" className="block text-sm font-medium text-foreground mb-2">
                文章内容
              </label>
              <Textarea
                id="content"
                value={content}
                onChange={(e) => setContent(e.target.value)}
                placeholder="在此处开始写作... 支持 Markdown 格式。"
                rows={15}
                required
              />
            </div>
            <div>
              <label htmlFor="tags" className="block text-sm font-medium text-foreground mb-2">
                标签
              </label>
              <Input
                id="tags"
                value={tags}
                onChange={(e) => setTags(e.target.value)}
                placeholder="例如：心情, 随笔, 技术 (用逗号分隔)"
              />
            </div>
            <div>
              <Button type="submit" disabled={isSubmitting} className="w-full">
                {isSubmitting ? '更新中...' : '更新文章'}
              </Button>
            </div>
          </form>
        </CardContent>
      </Card>
    </div>
  );
}
